import 'package:flutter/material.dart';

class AsyncLoadPage extends StatefulWidget {
  const AsyncLoadPage({Key? key}) : super(key: key);

  @override
  State<AsyncLoadPage> createState() => _AsyncLoadPageState();
}

class _AsyncLoadPageState extends State<AsyncLoadPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('异步UI更新'),
        ),
        body: Center(
            child: Column(
          children: [_futureBuilder(), _streamBuilder()],
        )));
  }

  Future<String> mockNetworkData() async {
    return Future.delayed(const Duration(seconds: 2), () => "我是从互联网上获取的数据");
  }

  _futureBuilder() {
    return Container(
      height: 300,
      width: 300,
      color: Colors.amber,
      child: Center(
        child: FutureBuilder<String>(
          future: mockNetworkData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            // 请求已结束
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                // 请求失败，显示错误
                return Text("Error: ${snapshot.error}");
              } else {
                // 请求成功，显示数据
                return Text("Contents: ${snapshot.data}");
              }
            } else {
              // 请求未结束，显示loading
              return const SizedBox(
                  width: 50, height: 50, child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }

  Stream<int> counter() {
    return Stream.periodic(const Duration(seconds: 1), (i) {
      return i;
    });
  }

  _streamBuilder() {
    return Container(
        height: 300,
        width: 300,
        color: Colors.green,
        child: Center(
            child: StreamBuilder<int>(
          stream: counter(),
          builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
            if (snapshot.hasError) return Text('Error: ${snapshot.error}');
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return const Text('没有Stream');
              case ConnectionState.waiting:
                return const Text('等待数据...');
              case ConnectionState.active:
                return Text('active: ${snapshot.data}');
              case ConnectionState.done:
                return const Text('Stream 已关闭');
            }
          },
        )));
  }
}
